
import { Component, OnInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import 'rxjs/add/operator/toPromise';
declare const $: any;
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDropDownBoxComponent } from 'devextreme-angular';
import * as ganttCharts from 'assets/visavail/js/ganttCharts.js';
import { Observable } from 'rxjs/Rx';
@Component({
    selector: 'app-report-gantry',
    templateUrl: './gantry.component.html',
    styleUrls: ['./gantry.component.scss']
})

export class GantryComponent implements OnInit {
    title = '机械手';
    public gantryList: any[];
    public gantryCyclerList: any[];
    public gantrys: any[] = [];
    public gantrySel: any;
    public chartGantry;
    public chartGanttOpt;
    public echartsInstance;

    categories = [];
    types = [
        { name: 'Inuse', color: '#f00' },
        { name: 'Idle', color: '#0f0' },
        { name: 'Overlap', color: '#00f' },
    ];

    /*生产线 - 班次*/
    public subAreaItems: SubArea[];
    public shiftItems: any[];
    public equipemntItems: TVResource[] = [];
    public subAareSelected: any;
    public shiftSelected: any;
    public equipmentSelected: TVResource[];

    @ViewChild('dddb') dddb: DxDropDownBoxComponent;

    constructor(private commServices: CommService) {
    }
    ngOnInit() {
        this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD HH:mm');

        $('#DateTimeRange').val('');

        this.shiftItems = this.commServices.shifts;
        this.shiftSelected = this.shiftItems[0];
        this.subAreaItems = this.commServices.getSubAreas();
        this.subAareSelected = this.subAreaItems[0];
        this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
        this.equipmentSelected = this.equipemntItems;
        this.getGantrys();
    }

    clearEquipmentSelected() {
        this.equipmentSelected = [];
    }
    equipmentSelectedOk() {
        this.dddb.instance.close();
    }

    onSubAreaSelectedChange(subArea: any): void {
        this.equipemntItems = this.commServices.getTVResourceBySubArea(subArea.value.subArea);
        this.equipmentSelected = this.equipemntItems;
    }
    /**
     * 获取表格数据
     */
    getReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        queryModel.shift = this.shiftSelected.shiftId;
        queryModel.tag = this.gantrySel.gantry;
        this.commServices
            .getList(queryModel, ReportUrls.GantryList)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.gantryList = model.data;
                    this.initChartOpt(this.gantryList);
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    getCyclerReportData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        queryModel.queryResourceIds = [this.gantrySel.gantry];
        queryModel.shift = this.shiftSelected.shiftId;
        queryModel.tag = this.gantrySel.gantry;
        this.commServices
            .getList(queryModel, ReportUrls.GantryCycler)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.gantryCyclerList = model.data;
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    getGantrys(): void {
        this.commServices
            .doGet(ReportUrls.Gantrys)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    this.gantrys = model.data;
                    this.gantrySel = this.gantrys[0];
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }

    getTime(id: any): String {
        const timerange: String = $('#' + id).val();
        return timerange;
    }

    // tslint:disable-next-line:member-ordering
    typesMap = new Map<string, number>();
    initChartOpt(gantryList) {
        const data = [];
        this.categories = [];
        this.categories.push('汇总');

        let min = 0;
        let max;

        let statusArr = [];

        gantryList.forEach(e => {
            if (!this.typesMap.has(e.opName)) {
                this.typesMap.set(e.opName, 0);
                this.categories.push(e.opName);
            }
            if (this.typesMap.get(e.opName) === 0) {
                this.typesMap.set(e.opName, e.endTime);
            }
            const caterotyIndex = this.categories.findIndex(el => el === e.opName);
            if (caterotyIndex !== -1) {
                if (min === 0) {
                    min = e.startTime;
                } else {
                    min = Math.min(min, e.startTime);
                }
                max = Math.max(max, e.endTime);
                // 计算空闲时间段
                if (e.endTime !== this.typesMap.get(e.opName) && e.startTime - this.typesMap.get(e.opName) > 0) {
                    data.push({
                        name: e.opName,
                        status: 'Idle',
                        value: [
                            caterotyIndex,
                            this.typesMap.get(e.opName),
                            e.startTime,
                            (e.startTime - this.typesMap.get(e.opName)) / 1000 // 持续时间
                        ],
                        itemStyle: {
                            normal: {
                                color: '#0f0'
                            }
                        }
                    });
                    this.typesMap.set(e.opName, e.endTime);
                }
                // 使用时间段
                data.push({
                    name: e.opName,
                    status: 'Inuse',
                    value: [
                        caterotyIndex,
                        e.startTime,
                        e.endTime,
                        e.duration
                    ],
                    itemStyle: {
                        normal: {
                            color: '#f00'
                        }
                    }
                });
            }
        });

        // let all = [];

        // data.forEach(e => {
        //     // statusArr.push({
        //     //     startTime: e.value[1],
        //     //     endTime: e.value[2],
        //     //     status: e.status
        //     // });
        //     all.push({ data: e.value[1], status: e.status });
        //     all.push({ data: e.value[2], status: e.status });
        // });

        // all = all.sort((a, b) => a.data - b.data);
        // for (let i = 0; i < all.length; i++) {
        //     if (i + 1 < all.length) {
        //         debugger
        //         const start = all[i];
        //         const end = all[i + 1];
        //         data.push({
        //             name: '汇总',
        //             status: 'Inuse',
        //             value: [
        //                 this.categories.findIndex(el => el === '汇总'),
        //                 start,
        //                 end,
        //                 (end - start) / 1000
        //             ],
        //             itemStyle: {
        //                 normal: {
        //                     color: '#f00'
        //                 }
        //             }
        //         });
        //     }
        // }
        // const tempTime = {
        //     startTime: 0,
        //     endTime: 0,
        //     count: 0
        // };
        // 2017-07-21 10:00 - 2017-07-21 14:30

        this.chartGanttOpt = ganttCharts.ganttEcharts('机械手图表', this.echartsInstance, this.categories, this.types, data, min, 'yyyy-MM-dd');
    }


    pushToRang(arr, startTime, endTime, statusCount) {
        arr.push({
            name: '汇总',
            status: status,
            value: [
                0,
                startTime,
                endTime,
                endTime - startTime
            ],
            itemStyle: {
                normal: {
                    // color: statusCount >= 2 ? '#00f' : statusCount === 1 ? '#f00' : '#0f0'
                    color: statusCount === 0 ? '#0f0' : '#f00'// this.getRandomColor()
                }
            }
        });
    }

    /**ECharts图表相关*/
    onChartInit(index: String, echartsIntance: any): void {
        this.echartsInstance = echartsIntance;
        Observable.fromEvent(window, 'resize')
            .debounceTime(100) // 以免频繁处理
            .subscribe((event) => this.echartsInstance.resize());
    }

    getRandomColor() {
        const colorValue = '0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f';
        const colorArray = colorValue.split(',');
        let color = '#';
        for (let i = 0; i < 6; i++) {
            color += colorArray[Math.floor(Math.random() * 16)];
        }
        return color;
    }

    onExporting(e) {
        e.fileName = e.fileName + new Date().toISOString().replace(/[\-\:\.]/g, '').split('T')[0];
    }
}
